package com.whately.core.base.exception.handler;

import com.whately.core.base.model.ApiResponse;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 *全局异常处理。
 *
 */
@ControllerAdvice
public class GlobalControllerExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 错误信息的构建工具.
     */
    @Autowired
    private ErrorInfoBuilder errorInfoBuilder;


    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Method method = e.getParameter().getMethod();
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("handleMethodArgumentNotValidException {} ,{} ",method.getName() , message);

        return ApiResponse.builder().code(400).message(message).build() ;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResponse error(HttpServletRequest request, HttpServletResponse response, Exception e) {
        ErrorInfo errorInfo= errorInfoBuilder.getErrorInfo(request,e);

        //把请求状态都设置为200
        response.setStatus(HttpStatus.SC_OK);
        //response.setStatus(errorInfo.getStatusCode());
        return ApiResponse.builder().code(errorInfo.getApiResponseCode()).message(errorInfo.getApiResponseMessage()).data(errorInfo).build();
    }


}
